from django.shortcuts import render, redirect
from .models import ToDo

# Create your views here.


def home(request):
    content = {'ToDoList': ToDo.objects.all()}
    if request.method == "POST":
        method = request.POST['Method']
        if method == "Add":
            content = add(request, content)  # 新增ToDo
        elif method == "Edit":
            content = edit(request, content)    # 修改已有ToDo
        elif method == "Del":
            content = delete(request, content)    # 删除已有ToDo
        elif method == "Change":
            content = change(request, content)    # 切换ToDo完成状态
    return render(request, 'todolist/home.html', content)


def about(request):
    return render(request, 'todolist/about.html')


def add(request, content):
    '新增ToDo'
    todoStr = request.POST['NewToDo']
    if todoStr == "":
        content['Warn'] = '请输入内容'
    else:
        row = ToDo(todo=todoStr, isDone=False)
        row.save()
        content['ToDoList'] = ToDo.objects.all()
    return content


def edit(request, content):
    '修改ToDo'
    todoStr = request.POST['EditText']
    idStr = request.POST['EditId']
    isOk = False
    if todoStr == "":
        content['Warn'] = '请输入内容'
    elif idStr == "":
        content['Warn'] = '修改失败'
    else:
        try:
            row = ToDo.objects.get(id=int(idStr))
            row.todo = todoStr
            row.save()
        except Exception as e:
            content['Warn'] = '修改失败' + str(e.args)
    content['ToDoList'] = ToDo.objects.all()
    return content


def change(request, content):
    '切换ToDo完成状态'
    idStr = request.POST['ChangeId']
    if idStr == "":
        content['Warn'] = '更新失败'
    else:
        try:
            row = ToDo.objects.get(id=int(idStr))
            row.isDone = not row.isDone
            row.save()
        except Exception as e:
            content['Warn'] = '更新失败' + str(e.args)
    content['ToDoList'] = ToDo.objects.all()
    return content


def delete(request, content):
    '删除ToDo'
    idStr = request.POST['DelId']
    if idStr == "":
        content['Warn'] = '删除失败'
    else:
        try:
            row = ToDo.objects.get(id=int(idStr))
            row.delete()
        except Exception as e:
            content['Warn'] = '删除失败' + str(e.args)
    content['ToDoList'] = ToDo.objects.all()
    return content
